<!--稿件发布页-->
<template>
  <h1 style="color:orange;">{{ content.id==null?'发布内容页面':'修改内容页面' }}</h1>
  <el-form label-width="100px">
    <el-form-item label="文章标题">
      <el-input placeholder="请输入文章标题" v-model="content.title"></el-input>
    </el-form-item>
    <el-form-item label="文章类型">
      <!-- :disabled="content.id!=null" id不为空也就是修改时,禁止修改文章类型     -->
      <el-radio-group @change="typeChange()" :disabled="content.id!=null" v-model="content.type">
<!--        <el-radio-button label="1">烘焙食谱</el-radio-button>-->
<!--        <el-radio-button label="2">烘焙视频</el-radio-button>-->
<!--        <el-radio-button label="3">行业资讯</el-radio-button>-->
        <el-radio-button v-for="c of catTypeArr" :label="c.type">{{c.name}}</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select v-model="content.categoryId" placeholder="请选择">
<!--        <el-option label="面包" value="1"></el-option>-->
<!--        <el-option label="小食" value="2"></el-option>-->
        <el-option v-for="c in categoryArr" :label="c.name" :value="c.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="封面">
      <img v-if="content.id!=null&&fileList.length==0"
          :src="'http://localhost:8080'+content.imgUrl"
          style="width: 145px;height: 145px;margin-right:10px;">
      <!--封面上传开始-->
      <el-upload
          v-model:file-list="fileList"
          action="http://localhost:8080/v1/upload"
          name="file"
          limit="1"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
      </el-dialog>
      <!--封面上传结束-->
    </el-form-item>

    <!-- 视频上传开始  -->
    <el-form-item label="视频" v-show="content.type==2">
      <video v-if="content.id!=null&&videoList.length==0"
      :src="'http://localhost:8080'+content.videoUrl"
      style="width:300px;margin-right:10px;"
      type="video/mp4" controls></video>
      <el-upload
          v-model:file-list="videoList"
          action="http://localhost:8080/v1/upload"
          name="file"
          limit="1"
          accept="video/*"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-button type="warning">点击上传视频</el-button>
        <div>(只能上传不超过100M的mp4文件)</div>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
      </el-dialog>
    </el-form-item>
    <!-- 视频上传结束  -->
    <el-form-item label="文章内容" v-show="content.type!=2">
      <div ref="editorDiv"></div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="post()">{{ content.id==null?'发布内容':'修改内容' }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import Editor from 'wangeditor'
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";
import router from "@/router";


//创建响应式变量,代表页面的div元素
const editorDiv = ref(null);
//用来保存一会创建好的富文本编辑器对象
let editor = null;
//挂载完毕立即执行的方法
onMounted(()=>{
  editor = new Editor(editorDiv.value);
  editor.config.placeholder="请输入内容详情";
  editor.create();
})

const catTypeArr = ref([]);
const categoryArr = ref([]);
const content = ref({title:'',type:'1',categoryId:''});
//当点击的文章类型发生改变，获取对应类型的二级分类
const typeChange = ()=>{
  //加这句为了防止切换一级分类时把原来的二级分类id带过去
  content.value.categoryId='';
  //发请求获取二级分类
  axios.get('http://localhost:8080/v1/categories/'+content.value.type+'/sub')
      .then((response)=>{
        if(response.data.code==2001){
          categoryArr.value = response.data.data;
        }
      })
}

onMounted(()=>{
  //当以get请求携带参数过来时，此方式可获取到?后参数
  if(location.search.includes('id')){
    let id = new URLSearchParams(location.search).get('id');
    axios.get('http://localhost:8080/v1/contents/'+id+'/update')
    .then((response)=>{
      if(response.data.code==2001){
        console.log(response.data.data);
        //根据id查询到的内容装到content中回显在页面上
        content.value = response.data.data;
        //把获取到的当前文章内容回显到富文本编辑器中
        editor.txt.html(content.value.content);
        //发请求获取二级分类
        //这里是为了解决二级分类无法正常回显的问题，默认type1下没有其它两种类型的二级分类，需要获取当前type重新拿到二级分类
        axios.get('http://localhost:8080/v1/categories/'+content.value.type+'/sub')
            .then((response)=>{
              if(response.data.code==2001){
                categoryArr.value = response.data.data;
              }
            })
      }
    })
  }
  //发请求获取二级分类
  axios.get('http://localhost:8080/v1/categories/1/sub')
  .then((response)=>{
    if(response.data.code==2001){
      categoryArr.value = response.data.data;
    }
  })

  axios.get('http://localhost:8080/v1/categories/type')
  .then((response)=>{
    if(response.data.code==2001){
      catTypeArr.value = response.data.data;
    }
  })
})


const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

//完成删除图片的方法
const handleRemove = (uploadFile) => {
  let imgUrl = uploadFile.response.data;
  axios.post('http://localhost:8080/v1/remove?imgUrl='+imgUrl)
  .then((response)=>{
    if(response.data.code==2001){
      ElMessage.success('服务器删除成功!');
    }
  })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
//定义视频数组
const videoList = ref([]);
//完成发布功能
const post = ()=>{
  //发布内容之前必须登录!
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if(user==null){
    ElMessage.error('请先登录!');
    router.push('/login');
    return;
  }
  //如果已登录，存用户id到content中
  content.value.userId=user.id;

  if(content.value.title.trim()==''){ElMessage.error('请输入标题!');return;}
  if(content.value.categoryId==''){ElMessage.error('请选择二级分类!');return;}
  /*判断是发布还是修改 如果是修改 可以延用之前的封面图片*/
  if(content.value.id==null){//新发布
    if(fileList.value.length==0){ElMessage.error('请上传封面图片!');return;}
    //获取封面图片路径，装入content内容对象中
    let imgUrl = fileList.value[0].response.data;
    content.value.imgUrl = imgUrl;
  }else{//修改
    if(fileList.value.length>0){
      let imgUrl = fileList.value[0].response.data;
      content.value.imgUrl = imgUrl;
    }
  }

  //判断是视频还是文章
  if(content.value.type==2){//视频
    if(content.value.id==null){//新发布
      if(videoList.value.length==0){ElMessage.error('请先选择视频文件!');return;}
      let videoUrl = videoList.value[0].response.data;
      content.value.videoUrl = videoUrl;
    }else{//修改
      if(videoList.value.length>0){
        let videoUrl = videoList.value[0].response.data;
        content.value.videoUrl = videoUrl;
      }
    }

  }else{//文章
    //从富文本编辑器中获取文章内容与摘要
    content.value.content = editor.txt.html();
    content.value.brief = editor.txt.text().slice(0, 30);
  }
  //发请求
  let data = qs.stringify(content.value);
  console.log(data);
  axios.post('http://localhost:8080/v1/contents/add-new',data)
      .then((response)=>{
        if(response.data.code==2001){
          ElMessage.success(content.value.id==null?'发布成功!':'修改成功!');
          //发布成功后要判断来源，从发布页、修改过来，回到稿件管理页面;从后台内容管理页面过来，回到后台内容页
          router.push('/personal/management');
          if(localStorage.from!=null&&localStorage.from=='admin'){
            router.push('/admin/content')
            localStorage.from=null;

          }else {
            router.push('/personal/management');
          }
        }
      })
}
</script>

<style scoped>

</style>